package com.wxzz.elearing.course.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.wxzz.elearing.course.dto.CurriculumSectionTopicDto;
import com.wxzz.elearing.course.dto.UserCurriculumDto;
import com.wxzz.elearing.course.dto.WxUserCurriculumDto;
import com.wxzz.elearing.course.entity.*;
import com.wxzz.elearing.course.mapper.CurriculumMapper;
import com.wxzz.elearing.course.mapper.CurriculumSectionMapper;
import com.wxzz.elearing.course.mapper.WxUserCurriculumDataMapper;
import com.wxzz.elearing.course.mapper.WxUserCurriculumMapper;
import com.wxzz.elearing.course.service.ICurriculumService;
import com.wxzz.elearing.course.service.IWxUserCurriculumService;
import com.wxzz.elearing.course.service.openfeign.IWxPayFeign;
import com.wxzz.elearing.course.service.openfeign.IWxUserApiFeign;
import com.wxzz.elearning.common.aop.Idempotent;
import com.wxzz.elearning.common.constants.OrderConstants;
import com.wxzz.elearning.common.constants.RedisConstants;
import com.wxzz.elearning.common.exception.ServiceException;
import com.wxzz.elearning.common.utils.CodeGenerateUtils;
import com.wxzz.elearning.common.utils.IPUtils;
import com.wxzz.elearning.common.utils.OpenFeignUtil;
import com.wxzz.elearning.common.vo.JgPageVo;
import com.wxzz.elearning.common.vo.ReturnVO;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 我的课程
 * 内部课程（企业自己发布用户看过的课程）
 * 外部课程（自己购买的和企业购买的平台课程，这里的平台课程是看过的) 服务实现类
 * </p>
 *
 * @author
 * @since 2021-03-15
 */
@Service

public class WxUserCurriculumServiceImpl extends ServiceImpl<WxUserCurriculumMapper, WxUserCurriculum> implements IWxUserCurriculumService {

    @Autowired
    private WxUserCurriculumMapper wxUserCurriculumMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ICurriculumService curriculumService;

    @Autowired
    private CurriculumSectionMapper curriculumSectionMapper;

    @Override
    public ReturnVO<JgPageVo<List<Curriculum>>> listWxUserCurriculumByWxUserId(Long wxUserId, WxUserCurriculumDto wxUserCurriculumDto) {
        PageHelper.startPage(wxUserCurriculumDto.getCurPage(), wxUserCurriculumDto.getMaxPage());
        List<Curriculum> curriculumList = wxUserCurriculumMapper.listCurriculumByWxUserId(wxUserId, wxUserCurriculumDto);
        for (Curriculum curriculum : curriculumList) {
            BigDecimal studySchedule = curriculumService.getStudySchedule(wxUserId, curriculum.getId());
            curriculum.setStudySchedule(studySchedule);
            //课程时长
            List<CurriculumSection> curriculumSectionList = curriculumSectionMapper.selectList(new LambdaQueryWrapper<CurriculumSection>().eq(CurriculumSection::getCurriculumId, curriculum.getId()));
            Long countTime = 0L;
            for (CurriculumSection curriculumSection : curriculumSectionList) {
                countTime = countTime + curriculumSection.getVideoTime();
            }
            curriculum.setCurriculumTime((double) countTime / 60);
            //章节数量
            Integer sectionCount = curriculumSectionMapper.selectCount(new LambdaQueryWrapper<CurriculumSection>().eq(CurriculumSection::getCurriculumId, curriculum.getId()));
            curriculum.setCurriculumSectionNum(sectionCount);
            //课件
            //学习人数
            Integer curriculumStudyNum = wxUserCurriculumMapper.selectCount(new LambdaQueryWrapper<WxUserCurriculum>()
                    .eq(WxUserCurriculum::getCurriculumId, curriculum.getId())
                    .eq(WxUserCurriculum::getStatus, 1));
            curriculum.setCurriculumStudyNum(curriculumStudyNum);
        }
        return new ReturnVO("查询我的课程", new JgPageVo(new PageInfo<>(curriculumList)));
    }

    @Override
    public ReturnVO saveBox(Long wxUserId, Integer saveType, List<CurriculumSectionTopic> curriculumSectionTopics) {
        redisTemplate.opsForValue().set(RedisConstants.SAVE_TYPE + saveType + RedisConstants.SAVE_BOX + wxUserId, JSONObject.toJSONString(curriculumSectionTopics));
        return new ReturnVO("保存草稿成功", null);
    }


    @Autowired
    private IWxPayFeign wxPayFeign;

    @Autowired
    private CurriculumMapper curriculumMapper;

    /**
     * 幂等处理
     *
     * @param wxUserId
     * @param curriculumId
     * @return
     */
    @Idempotent
    @GlobalTransactional//开启全局事务
    @Transactional //开启本地事务
    @Override
    public ReturnVO saveWxUserCurriculum(Long wxUserId, Long curriculumId) {
        //接口幂等处理
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(RedisConstants.WX_USER_COMMENT + wxUserId, String.valueOf(wxUserId), 5, TimeUnit.SECONDS);
        if (!Boolean.TRUE.equals(aBoolean)) {
            throw new ServiceException("请重新进入确认是否已经支付成功,以免重复支付");
        }
        Curriculum curriculum = curriculumMapper.selectById(curriculumId);
        Optional.ofNullable(curriculum).orElseThrow(() -> new ServiceException("该课程不存在"));
        WxUserCurriculum wxUserCurriculum = wxUserCurriculumMapper.selectOne(new LambdaQueryWrapper<WxUserCurriculum>()
                .eq(WxUserCurriculum::getWxUserId, wxUserId).eq(WxUserCurriculum::getCurriculumId, curriculumId));
        if (wxUserCurriculum == null) {
            WxUserCurriculum save = new WxUserCurriculum();
            save.setCurriculumId(curriculumId);
            save.setWxUserId(wxUserId);
            wxUserCurriculumMapper.insert(save);
            wxUserCurriculum = save;
        } else {
            if (wxUserCurriculum.getStatus() == 1) {
                throw new ServiceException("该课程已购买");
            }
        }
        //调用支付模块 创建订单 赋值订单id 以下操作在支付成功回调中
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Map<String, String> map = new HashMap();
        map.put("ipaddress", IPUtils.getIpAddr(request));
        map.put("wxUserId", String.valueOf(wxUserId));
        map.put("serialid", CodeGenerateUtils.generateProductCode());
        //如果免费直接返回购买成功
        if ("0.00".equals(curriculum.getCurriculumPrice().toString())) {
            wxUserCurriculum.setStatus(1);
            wxUserCurriculumMapper.updateById(wxUserCurriculum);
            return new ReturnVO("购买成功", 1);
        }
        map.put("businessId", String.valueOf(curriculumId));
        map.put("payMoney", String.valueOf(curriculum.getCurriculumPrice()));
        map.put("orderTitle", "用户购买课程id:" + curriculumId);
        map.put("modelType", OrderConstants.MODEL_TYPE_CURRICULUM.toString());
        map.put("userType", OrderConstants.USER_TYPE_PLATFORM_WX.toString());
        Map<String, String> result = wxPayFeign.orderPay(map);//记录 undo_log
        wxUserCurriculum.setUserOrderId(Long.valueOf(result.get("orderId")));
        wxUserCurriculumMapper.updateById(wxUserCurriculum);
        return new ReturnVO("订单生成成功", result.get("returnJson"));
    }

    @Override
    public ReturnVO collectCurriculum(Long wxUserId, Long curriculumId) {
        WxUserCurriculum wxUserCurriculum = wxUserCurriculumMapper.selectOne(new LambdaQueryWrapper<WxUserCurriculum>()
                .eq(WxUserCurriculum::getWxUserId, wxUserId)
                .eq(WxUserCurriculum::getCurriculumId, curriculumId));
        Optional.ofNullable(wxUserCurriculum).ifPresent(c -> {
            //点赞或取消点赞
            if (c.getIsCollect() == 0) {
                c.setIsCollect(1);
            } else {
                c.setIsCollect(0);
            }
            wxUserCurriculumMapper.updateById(c);
        });
        return new ReturnVO("点赞或取消点赞成功", curriculumId);
    }

    @Autowired
    private IWxUserApiFeign wxUserApiFeign;

    @Autowired
    private WxUserCurriculumDataMapper wxUserCurriculumDataMapper;

    @Override
    public ReturnVO<JgPageVo<List<WxUserCurriculum>>> listWxUserCurriculum(UserCurriculumDto userCurriculumDto) {
        if (userCurriculumDto.getDocentId() == null) {
            throw new ServiceException("请传入讲师id");
        }
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isNotBlank(userCurriculumDto.getPhone())) {
            map.put("phone", userCurriculumDto.getPhone());
        }
        if (StringUtils.isNotBlank(userCurriculumDto.getNickname())) {
            map.put("nickname", userCurriculumDto.getPhone());
        }
        //远程调用查询用户列表
        ReturnVO<List<Long>> listReturnVO = wxUserApiFeign.listWxUserByMap(map);
        //若调用方没查到数据直接返回空数组
        if (listReturnVO.getData() == null || listReturnVO.getData().size() == 0) {
            return new ReturnVO("参与学习人查询成功", new JgPageVo<>(new PageInfo(Lists.newArrayList())));
        }
        PageHelper.startPage(userCurriculumDto.getCurPage(), userCurriculumDto.getMaxPage());
        //根据讲师id和用户id查询数据
        List<WxUserCurriculum> wxUserCurricula = wxUserCurriculumMapper.listWxUserCurriculumByDocent(userCurriculumDto.getDocentId(), listReturnVO.getData());
        for (WxUserCurriculum wxUserCurriculum : wxUserCurricula) {
            ReturnVO<String> stringReturnVO = wxUserApiFeign.selectWxUserByWxUserId(wxUserCurriculum.getWxUserId());
            JSONObject jsonObject = OpenFeignUtil.getJSONObject(stringReturnVO);
            //用户信息
            wxUserCurriculum.setNickname(jsonObject.getString("nickname"));
            wxUserCurriculum.setIcon(jsonObject.getString("icon"));
            wxUserCurriculum.setPhone(jsonObject.getString("phone"));
            wxUserCurriculum.setEnterpriseName(jsonObject.getString("enterpriseName"));
            //统计学习时长
            WxUserCurriculumData wxUserCurriculumData = wxUserCurriculumDataMapper.selectOne(new LambdaQueryWrapper<WxUserCurriculumData>()
                    .eq(WxUserCurriculumData::getWxUserId, wxUserCurriculum.getWxUserId()));
            if (wxUserCurriculumData != null) {
                wxUserCurriculum.setStudyTime((double) wxUserCurriculumData.getStudyTime() / 1000 / (60 * 60));
                wxUserCurriculum.setTodayStudyTime((double) wxUserCurriculumData.getTodayStudyTime() / 1000 / (60 * 60));
                wxUserCurriculum.setFinishClass(wxUserCurriculumData.getFinishClass());
            }
        }
        return new ReturnVO("参与学习人查询成功", new JgPageVo<>(new PageInfo(wxUserCurricula)));
    }

    @Transactional
    @Override
    public ReturnVO<String> handlerNotifyCurriculum(Long userOrderId) {
        WxUserCurriculum wxUserCurriculum = wxUserCurriculumMapper.selectOne(new LambdaQueryWrapper<WxUserCurriculum>()
                .eq(WxUserCurriculum::getUserOrderId, userOrderId));
        if (wxUserCurriculum == null) {
            throw new ServiceException("该订单id对应用户购课信息不存在");
        }
        wxUserCurriculum.setStatus(1);
        wxUserCurriculumMapper.updateById(wxUserCurriculum);
        return new ReturnVO("购课信息状态修改成功", null);
    }

    @Override
    public ReturnVO<String> selectDocentById(Long docentId) {
        Integer allCurriculumNum = curriculumMapper.selectCount(new LambdaQueryWrapper<Curriculum>()
                .eq(Curriculum::getDocentId, docentId));
        Integer curriculumStudyNum = curriculumMapper.selectCountStudyNum(docentId);
        Map returnJson = new HashMap();
        //总讲数
        returnJson.put("allCurriculumNum", allCurriculumNum);
        //学习人数
        returnJson.put("curriculumStudyNum", curriculumStudyNum);
        return new ReturnVO("根据讲师id查询总讲数和参与学习人数查询成功", JSONObject.toJSONString(returnJson));
    }

    @Override
    public ReturnVO<JSONObject> selectCurriculumByOrderId(Long orderId) {
        WxUserCurriculum wxUserCurriculum = wxUserCurriculumMapper.selectOne(new LambdaQueryWrapper<WxUserCurriculum>()
                .eq(WxUserCurriculum::getUserOrderId, orderId));
        if (wxUserCurriculum != null) {
            Curriculum curriculum = curriculumMapper.selectById(wxUserCurriculum.getCurriculumId());
            if (curriculum != null) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("enterpriseId", curriculum.getEnterpriseId());
                jsonObject.put("curriculumType", curriculum.getCurriculumType());
                return new ReturnVO<>("课程信息查询成功", jsonObject);
            }
        }
        throw new ServiceException("课程信息不存在");
    }
}
